<template>
  <div class="home" :changeModuleShow="changeModuleShow" :finishInput="finishInput">
    <homeHeader></homeHeader>
     <div class="amap-page-container">
      <el-amap ref="maps" vid="amap" :plugin="plugin" :zoom="zoom" class="amap-demo" :center="mapCenter" :events="events" :amap-manager="amapManager" :map-style="freshs">
        <el-amap-marker :position="mapCenter" :visible="marker[0].visible" :icon="marker[0].icon"></el-amap-marker>
        <!-- <el-amap-marker v-for="marker in markers" :position="marker" :key="marker.id"></el-amap-marker> -->
      </el-amap>
    </div>
    <flightInfo v-if="showFlight" v-on:hidetitles="hidetitles"></flightInfo>
    <timeInfo v-if="showTimeInfo"></timeInfo>
    <carpool :money="Money" v-if="showCarpool"></carpool>
    <chooseType v-if="showType" v-on:getPreinput="getPreinput"></chooseType>
    <cancel v-if="showCancel"></cancel>
    <tips v-if="showTips"></tips>
    <nocall v-if="showNoCall"></nocall>
    <reservation v-if="showSuccess"></reservation>
    <orderDetails v-if="showDriver"></orderDetails>
    <arrivalTime v-if="showArrival"></arrivalTime>
  </div>
</template>

<script>
// 首页头信息
import homeHeader from 'base/home-header/home-header'
// 选择类型
import chooseType from 'base/choose-type/choose-type'
// 是否拼车
import carpool from 'base/carpool/carpool'
// 取消订单
import cancel from 'base/cancel/cancel'
// 左侧个人中心
import bar from 'base/home-bar/home-bar'
// 显示输入航班信息
import flightInfo from 'base/flight-info/flight'
// 显示输入时间
import timeInfo from 'base/flight-info/flight-info'
// 乘车提示
import tips from 'base/need-know/need-know'
// 没有响应
import nocall from 'base/nocall/nocall'
// 预约成功
import reservation from 'base/suc-reservation/suc-reservation'
// 接单司机信息
import orderDetails from 'base/order-details/order-details'
// 显示到达后多久上车
import arrivalTime from 'base/flight-info/arrival-time'

import axios from 'axios'
// 引入这个页面需要的方法库
import VueAMaps from 'vue-amap'

import {mapGetters, mapMutations} from 'vuex'

import {getFlightPrice} from 'api/api'

let amapManager = new VueAMaps.AMapManager()
 /* eslint-disable */
export default {
  data () {
    let self = this
    return {
     marker: [
        {
          // content:'<p>hello</p>',
          visible:true,
          icon:'../../../static/img/location.png'
        }
      ],
      searchOption: {
        city: '武汉',
        citylimit: false
      },
      showFlight: false,
      changeNumber: false,
      mapCenter: [0, 0],
      lng: 114.36865,
      lat: 30.52874,
      zoom: 13,
      loaded: false,
      Money: '',
      freshs:'normal',
      amapManager,
      events: {
        init: (o) => {
          self.getcenters = o
        },
        dragging: (e) => {
          if(this.showState == 1){
            this.setShowSearchBox(true)
          }
          if(this.showState == 2){
            this.setShowEnd(true)
          }
          self.lng = self.getcenters.getCenter().lng
          self.lat = self.getcenters.getCenter().lat
          self.mapCenter = [self.lng, self.lat]
          self.loaded = true
          self.visible=true
          self.$nextTick()
        },
        dragend: (e) => {
          const _this = this
          const geocoder = new AMap.Geocoder({
          	radius: 1000,
            extensions: 'all',
            autoFitView:true
          })
          self.lng = self.getcenters.getCenter().lng
          self.lat = self.getcenters.getCenter().lat
          self.mapCenter = [self.lng, self.lat]
          self.loaded = true
          self.visible=true
          self.$nextTick()
        }
      },
      plugin: [{
        pName: 'Geolocation',
        zoom: 12,
        buttonPosition: 'LB',
        events: {
          init (o) {
            // o 是高德地图定位插件实例
            o.getCurrentPosition((status, result) => {
              if (result && result.position) {
                self.lng = result.position.lng
                self.lat = result.position.lat
                self.center = [self.lng, self.lat]
                self.loaded = true
                self.$nextTick()
              }
            })
          }
        }
      }]
    }
  },
  computed: {
    // 当用户完成全部输入的时候触发切换价格预估页面
    finishInput () {
      const _this = this
      if (this.pickType === 1) {
        console.log('接机')
        if (this.flightInfo && this.timeInfo && this.searchBoxInfo && this.destination) {
          // 路径规划、验证是否登录
            this.changeNumber = true
            var driving = new AMap.Driving({
              map:amapManager._map,
              extensions:"all",
              autoFitView:true
            })
            driving.search(new AMap.LngLat(localStorage.getItem('lng1'), localStorage.getItem('lat1')), new AMap.LngLat(localStorage.getItem('lng2'), localStorage.getItem('lat2')),function(status, result){
              if(result.info === 'OK'){
                _this.changeEstimatePrice()
                console.log('耗时:' + result.routes[0].time / 60)
                localStorage.setItem('timeConsuming',result.routes[0].time / 60)
                localStorage.setItem('dsitence',result.routes[0].distance /  1000)
                console.log('输入完' + result.routes[0].distance /  1000)
              }
            })
        }
      } else if (this.pickType === 2) {
        console.log('送机')
        if (this.timeInfo && this.searchBoxInfo && this.destination) {
            this.changeNumber = true
            var driving = new AMap.Driving({
              map:amapManager._map,
              extensions:"all",
              autoFitView:true
            })
            driving.search(new AMap.LngLat(localStorage.getItem('lng1'), localStorage.getItem('lat1')), new AMap.LngLat(localStorage.getItem('lng2'), localStorage.getItem('lat2')),function(status, result){
              if(result.info === 'OK'){
                _this.changeEstimatePrice()
                localStorage.setItem('dsitence',result.routes[0].distance /  1000)
              }
            })
        }
      }
    },
    // 计算页面中的module的显示
    changeModuleShow () {
      this.showFlight = this.showFlightInfo
      if (this.showSearchBox === true) {
      }
    },
    ...mapGetters([
      'showBar',
      'showFlightInfo',
      'showTimeInfo',
      'showSearchBox',
      'showEnd',
      'flightInfo',
      'timeInfo',
      'searchBoxInfo',
      'destination',
      'showTips',
      'showCarpool',
      'showCancel',
      'showNoCall',
      'showType',
      'showInType',
      'pickType',
      'carStartTime',
      'showSuccess',
      'showDriver',
      'showState',
      'userId',
      'showArrival',
      'arrivalInfo'
      // 'dsitence'
    ])
  },
  mounted () {
    this.deleteLogo()
    if (this.$route.query.orderNum) {
        localStorage.setItem('orderNum',this.$route.query.orderNum)
        this.setShowBar(false)
        this.setShowTips(false)
        this.setShowCarpool(false)
        this.setShowInType(true)
        this.setShowCancel(true)
        this.setShowType(false)
    }
  },
  created () {
    this.init()
  },
  /* eslint-disable */
  methods: {
    hidetitles () {
      this.setShowFlightInfo(false)
    },
    init () {
      this.setSearchBoxInfo('天河国际机场')
      localStorage.setItem('lat1','30.770054')
      localStorage.setItem('lng1','114.2142298')
    },
    //判断是否有进行中订单
    checkIshasOder () {
      const _this = this
      const passengerId = localStorage.getItem('userId')
      console.log(passengerId)
      axios.get('http://39.104.54.182:8080/ecar/r/passenger/' + passengerId + '/recover')
      .then((res) => {
        console.log(res)
      }).catch(error => {
        console.log(error)
      })
    },
    // 删除高德地图的logo
    deleteLogo () {
      let that = this
      localStorage.setItem('anthorpickType', 1)
      setTimeout(function () {
        let dingweiIcon = document.getElementsByClassName('amap-geolocation-con')[0]
        if (dingweiIcon) {
          dingweiIcon.style = "position: absolute; z-index: 9999; left: 10px; bottom: 220px;"
        }
      }, 1000)
    },
    getPreinput () {},
    // 搜索的输入框 触发的事件
    onSearchResultStart(pois) {
      alert('hello world')
      let locationName = pois[0].name
      if (this.showSearchBox === true) {
        localStorage.setItem('lat1',pois[0].lat)
        localStorage.setItem('lng1',pois[0].lng)
        console.log(localStorage.lat1)
        this.setSearchBoxInfo(locationName)
        this.setShowSearchBox(false)
        this.getDrinkeMap()
      } else {
        this.setDestination(locationName)
        this.getDrinkeMap()
        this.setShowEnd(false)
      }
      let latSum = 0
      let lngSum = 0
      if (pois.length > 0) {
        pois.forEach(poi => {
          let {lng, lat} = poi
          lngSum += lng
          latSum += lat
          // this.markers = []
          // this.markers.push([poi.lng, poi.lat])
        })
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        }
        this.mapCenter = [center.lng, center.lat]
        let sc = center.lat + ':' + center.lng
        console.log(sc)
        this.setStartCoor(sc)
      }
    },
    onSearchResultEnd(pois) {
      let locationName = pois[0].name
      console.log('hello world')
      if (this.showSearchBox === true) {
        console.log('hello world')
        localStorage.setItem('lat1',pois[0].lat)
        localStorage.setItem('lng1',pois[0].lng)
        this.setSearchBoxInfo(locationName)
        this.setShowSearchBox(false)
        this.getDrinkeMap()
        console.log('hello world')
        console.log(localStorage.getItem('lat1'))
      } else {
        console.log('hello world')
        this.lat2 = pois[0].lat
        this.lng2 = pois[0].lng
        localStorage.setItem('lat2',pois[0].lat)
        localStorage.setItem('lng2',pois[0].lng)
        this.getDrinkeMap()
        this.setDestination(locationName)
        this.setShowEnd(false)
      }
      let latSum = 0
      let lngSum = 0
      if (pois.length > 0) {
        pois.forEach(poi => {
          let {lng, lat} = poi
          lngSum += lng
          latSum += lat
          // this.markers = []
          // this.markers.push([poi.lng, poi.lat])
        })
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        }
        this.mapCenter = [center.lng, center.lat]
        let ec = center.lat + ':' + center.lng
        console.log(ec)
        this.setEndCoor(ec)
      }
    },
    // 路径规划
    getDrinkeMap () {
      let _this = this
  	  if (this.searchBoxInfo && this.destination) {
          amapManager._map.clearMap()
          var driving = new AMap.Driving({
            map:amapManager._map,
            extensions:"all",
            autoFitView:true
          })
          driving.search(new AMap.LngLat(localStorage.getItem('lng1'), localStorage.getItem('lat1')), new AMap.LngLat(localStorage.getItem('lng2'), localStorage.getItem('lat2')),function(status, result){
            if(result.info === 'OK'){
              localStorage.setItem('dsitence',result.routes[0].distance /  1000)
              console.log('路劲规划的:' + result.routes[0].distance /  1000)
            }
          })
        }
  	},
    // 当用户在首页输入完四个input框之后切换到车辆类型选择和价格预估页面
    changeEstimatePrice () {
      console.log('都输入完了')
      localStorage.setItem('flightInfo',this.flightInfo)
      localStorage.setItem('carStartTime',this.carStartTime)
      localStorage.setItem('pickType',this.pickType)
      localStorage.setItem('arrivalInfo',this.arrivalInfo)
      let distance = localStorage.getItem('dsitence')
      let timeConsuming = localStorage.getItem('timeConsuming')
      let distances = Number(distance)
      this.setOrderName(localStorage.user)
      this.setOrderPhone(localStorage.phone)
      let vm=this
      if (this.pickType === 1) {
        console.log('不跳啊')
        axios.post(getFlightPrice, {
          "param": {
            "fields": {
              "flightNo": this.flightInfo ? this.flightInfo : '',
              "date": this.carStartTime,
              "carLevel": 2,
              "serviceType": this.pickType,
              "preTime": timeConsuming,
              "distance": distances,
              "timeStamp": this.arrivalInfo
            }
          }
        })
        .then((res) => {
          console.log('resres')
          localStorage.setItem('prePrice', res.data.result.prePrice)
          vm.Money = localStorage.getItem('prePrice')
          if (vm.Money && vm.Money != 'undefined') {
            if (this.showInType === false) {
             this.setShowCarpool(true)
             this.setShowType(false)
            }
            return false
          } else {
            this.$createDialog({
              type: 'alert',
              title: '',
              content: '航班信息有误！',
              icon: 'cubeic-alert'
            }).show()
          }
        }).catch(error => {
          console.log('曙光')
          console.log(error)
        })
      }else if (this.pickType === 2){
        axios.post(getFlightPrice, {
        param: {
          fields: {
            carLevel: 2,
            serviceType: this.pickType,
            preTime: timeConsuming,
            distance: distances,
            timeStamp: this.carStartTime
          }
        }
      })
      .then(res => {
        if (this.showInType === false) {
          this.setShowCarpool(true);
          this.setShowType(false);
        }
        localStorage.setItem('prePrice', res.data.result.prePrice)
          vm.Money = localStorage.getItem('prePrice')
        })
        .catch(error => {
          console.log(error);
        });
      }
    },
    ...mapMutations({
      setShowFlightInfo: 'SET_SHOWFLIGHTINFO',
      setSearchBoxInfo: 'SET_SEARCHBOXINFO',
      setShowSearchBox: 'SET_SHOWSEARCHBOX',
      setShowEnd: 'SET_SHOWEND',
      setDestination: 'SET_DESTINATION',
      setEstimatePrice: 'SET_ESTIMATEPRICE',
      setShowCarpool: 'SET_SHOWCARPOOL',
      setShowType: 'SET_SHOWTYPE',
      setShowInType: 'SET_SHOWINTYPE',
      setCarStartTime: 'SET_CARSTARTTIME',
      setStartCoor: 'SET_STARTCOOR',
      setEndCoor: 'SET_ENDCOOR',
      setShowDriver: 'SET_SHOWDRIVER',
      setShowState: 'SET_SHOWSTATE',
      setShowArrival: 'SET_SHOWARRIVAL',
      setShowTips: 'SET_SHOWTIPS',
      setShowCancel: 'SET_SHOWCANCEL',
      setOrderName: 'SET_ORDERNAME',
      setOrderPhone: 'SET_ORDERPHONE',
      setShowBar: 'SET_SHOWBAR'
    })
  },
  components: {
    homeHeader,
    chooseType,
    carpool,
    cancel,
    bar,
    flightInfo,
    timeInfo,
    tips,
    nocall,
    reservation,
    orderDetails,
    arrivalTime
  }
}
</script>

<style  scoped lang="stylus" rel="stylesheet/stylus">
  .amap-demo
    height: 100vh
    width: 100%
  .search-box
    position: absolute
    top: 50px
    left: 10px
  .myPageTop
    position: fixed
    top: 50px
  .home
    width: 100%
    hieght: auto
    min-height: 100vh
    .map
      width: 100%
      height: 100vh
      min-height: calc(100vh - 44px)
      box-sizing: border-box
.amap-logo, .amap-copyright
  display: none
</style>